import {Hono} from "hono";
import {cleanName} from "@/lib/utils";
import {memoizedKplTopMix} from "@/backend/services/kpl-service";
import {memorizedETF, memorizedETFDown} from "@/backend/services/east-service";
import {getRankHist} from "@/backend/services/public";


const addLabelToETF = (plates: any, etfs: any) => {
    plates.forEach((plate: string) => {
        etfs.forEach((etf: { label: string; etf_name: string; }) => {
            if (!etf.etf_name.startsWith('#')) {
                etf.label = etf.etf_name.split("ETF", 1).at(0) || etf.etf_name;
            }
            if (!etf.etf_name.startsWith('#') && (plate.toLowerCase().includes(etf.label.toLowerCase()) || etf.etf_name.toLowerCase().includes(plate.toLowerCase()))) {
                // etf.label = plate;
                etf.etf_name = `#${etf.etf_name}`
            }
        })
    })
    return etfs;
}

export const etfRouter = new Hono()
    .get('/up', async (c) => {
        const {list: kplMixList} = await memoizedKplTopMix();
        const kplMixListNames: string[] = kplMixList.map((p: any) => cleanName(p[1]));
        const cached = await memorizedETF(true);
        const etfData = structuredClone(cached)
        addLabelToETF(kplMixListNames, etfData);
        // const etfDataFiltered = etfData.filter(e => e.etf_name !== '#')
        const uniqueEtf = etfData.filter((etf: any, index: any, selfArr: any) => etf.label !== "" && index === selfArr.findIndex((t: any) => t.label === etf.label))
        // console.log(uniqueEtf)
        return c.json({data: uniqueEtf});

    })
    .get("/down", async (c) => {
        const cached = await memorizedETFDown(100)
        // console.log(cached.length)
        const rankHist = await getRankHist()
        const etfData = structuredClone(cached)
        const filtered = etfData.filter((etf: { f14: string; f3: number; label: string; }) => {
            const _label = etf.f14.split('ETF').at(0) || '';
            for (const plate of rankHist) {
                if ((_label.toLowerCase().includes(plate.toLowerCase()) || plate.toLowerCase().includes(_label)) && (etf.f3 < 0)) {
                    etf.label = plate
                    return true
                }
            }
            etf.label = _label
            return false
        })
        const uniqueEtf = filtered.filter((etf: any, index: any, selfArr: any) => index === selfArr.findIndex((t: any) => t.label === etf.label))
        return c.json({data: uniqueEtf});
    })